﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using QDFeedParser;
using System.IO;
using System.Net;

namespace Codeplex_MSI_Autoupdate
{
    static class Program
    {
        static String CodePlexURL;
        static String ProgramName;
        static String CurrentVersion;
        static Boolean Prompt = false;
        static Boolean DirectDL = false;
        static String ParmPrompt = "Prompt";
        static String ParmAutoDL = "DirectDL";

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            int ArgsLength = Environment.GetCommandLineArgs().Length;
            //Checking for required parameter count
            if (ArgsLength < 4)
                throw new ArgumentException();
            String[] Args = Environment.GetCommandLineArgs();
            //Reading base values
            CodePlexURL = Args[1];
            ProgramName = Args[2];
            CurrentVersion = Args[3];
            //Reading optional switches
            if (ArgsLength > 4)
            {
                if (Args[4] == ParmPrompt)
                    Prompt = true;
                else if (Args[4] == ParmAutoDL)
                    DirectDL = true;
            }
            if (ArgsLength > 5)
            {
                if (Args[5] == ParmPrompt)
                    Prompt = true;
                else if (Args[5] == ParmAutoDL)
                    DirectDL = true;
            }
            //Basic URL check
            String CorrectedURL=null;
            if (!CodePlexURL.Contains("/"))
                CorrectedURL = CodePlexURL;
            else
            {
                foreach (String Fragment in CodePlexURL.Split('/'))
                    if (Fragment.EndsWith(".codeplex.com"))
                        CorrectedURL = Fragment.Replace(".codeplex.com", "");
            }
            //Fetch the releases feed
            IFeed Feed = new HttpFeedFactory().CreateFeed(new Uri("http://" + CorrectedURL + ".codeplex.com/project/feeds/rss?ProjectRSSFeed=codeplex%3a%2f%2frelease%2f" + CorrectedURL));
            if (Feed.Items.Count == 0)
                return;
            //Find the relevant feed items
            List<String[]> Releases = new List<String[]>();
            Double NumVersion;
            foreach (Rss20FeedItem Item in Feed.Items)
            {
                if (Item.Title.StartsWith("Released: "))
                {
                    String ReleaseName=Item.Title.Replace("Released: ", "");
                    if (ReleaseName.StartsWith(ProgramName))
                    {
                        String Version = ReleaseName.Replace(ProgramName + " ", "");
                        Version = Version.Split(' ')[0];
                        if (Double.TryParse(Version, out NumVersion))
                            Releases.Add(new String[2] { Version, Item.Link });
                    }
                }
            }
            if (Releases.Count == 0)
                return;
            //Find the latest release
            String[] HighestRelease = Releases[0];
            foreach (String[] Release in Releases)
            {
                if (HighestRelease[0].CompareTo(Release[0]) < 0)
                    HighestRelease = Release;
            }
            //Compare with the current version
            if (!(CurrentVersion.CompareTo(HighestRelease[0]) < 0))
                return;
            //Download the release page
            WebBrowser Container = new WebBrowser();
            Container.Navigate(HighestRelease[1]);
            Container.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(LoadAndParsePage);
            //Start the message pump to make the app wait
            Application.Run();
        }

        private static void LoadAndParsePage(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            HtmlDocument Page = ((WebBrowser)sender).Document;
            if (DirectDL)
            {
                String DLLink = Page.GetElementById("fileDownload0").GetAttribute("href");
                String RelNotes = Page.GetElementById("ReleaseNotes").GetElementsByTagName("div")[0].InnerText;
                if (!(Prompt && (MessageBox.Show("A new version of " + ProgramName + " is available!" +Environment.NewLine+ "Do you want to install it now?" + Environment.NewLine + Environment.NewLine + "Release notes:" + Environment.NewLine + RelNotes, ProgramName + " Update", MessageBoxButtons.YesNo) == DialogResult.No)))
                {
                    Process.Start(DLLink);
                    //Sadly, this doesn't work
                    //StartDL(DLLink);
                }
            }
            else
            {
                if (!(Prompt&&(MessageBox.Show("A new version of "+ProgramName+" is available!"+Environment.NewLine+"Do you want to go to the download page?",ProgramName+" Update",MessageBoxButtons.YesNo)==DialogResult.No)))
                    Process.Start(Page.Url.ToString());
            }
            //Have to quit manually due to the message pump running
            Application.Exit();
        }

        private static void StartDL(String DLLink)
        {
            String LocalFile = Path.GetTempFileName();
            new WebClient().DownloadFile(DLLink, LocalFile);
        }
    }
}
